from flask import Flask, render_template, request, redirect, url_for, session
import config
from models import User
from exts import db
from decorators import login_required
import re
import pymysql
import hashlib

pymysql.install_as_MySQLdb()

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        telephone = request.form.get('telephone')
        password = request.form.get('password')
        m1 = hashlib.md5()
        m1.update(password.encode("utf8"))
        pwd_md5 = m1.hexdigest()
        user = User.query.filter(User.telephone == telephone, User.password == pwd_md5).first()
        if user:
            session['user_telephone'] = user.telephone
            # 31天内都不需要登录
            session.permanent = True
            return redirect(url_for('index'))
        else:
            return u'手机号码或密码错误，请确认后再登录'


@app.route('/regist/', methods=['GET', 'POST'])
def regist():
    identification = '普通用户'
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        telephone = request.form.get('telephone')
        username = request.form.get('username')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        # 手机号正则验证
        phone_pat = re.compile('^(13\d|14[5|7]|15\d|166|17[3|6|7]|18\d)\d{8}$')

        res = re.search(phone_pat, telephone)

    # 手机号码验证，如果被注册就不能再注册
    user = User.query.filter(User.telephone == telephone).first()
    if user:
        return u'该手机号码已被注册'
    else:
        # password1和password2是否相等
        if password2 != password1:
            return u'两次密码不相同'
        elif username == '':
            return u'用户名不能为空'
        else:
            if not res:
                return u'手机号格式不对'
            else:
                # 密码加密存储
                m1 = hashlib.md5()
                m1.update(password1.encode("utf8"))
                pwd_md5 = m1.hexdigest()
                user = User(telephone=telephone, username=username, password=pwd_md5, identification=identification)
                db.session.add(user)
                db.session.commit()
                # 如果注册成功，跳转到登录页面
                return redirect(url_for('login'))


@app.route('/logout/')
def logout():
    # session.pop('user_telephone')
    session.clear()
    return redirect(url_for('login'))


@app.route('/question/')
@login_required
def question():
    if request.method == 'GET':
        return render_template('question.html')
    else:
        pass


# 上下文处理器 bilibili 09登录注销5min
@app.context_processor
def my_context_processor():
    user_telephone = session.get('user_telephone')
    if user_telephone:
        user = User.query.filter(User.telephone == user_telephone).first()
        if user:
            return {'user': user}
    return {}


if __name__ == '__main__':
    app.run()
